package com.uyayo.oms.system.controller;


import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.message.model.Tree;
import com.uyayo.framework.common.util.CodeUtil;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.vo.RoleVO;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.authority.entity.SysRole;
import com.uyayo.system.authority.entity.SysRoleResource;
import com.uyayo.system.authority.model.SysRoleCondition;
import com.uyayo.system.authority.service.SysRoleService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 
 * <p>
 * Title: SysRoleController
 * </p>
 * <p>
 * Description:角色的controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller("sysRoleController")
@RequiresAuthentication
@RequestMapping("/system/authority/role")
public class SysRoleController {

	@Autowired 
	private SysRoleService roleService;
	
	@Autowired
	private ParamBiz paramBiz;
	
	
	@RequestMapping(value="index",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:role:index")
	@MethodName(value="系统管理->权限管理->角色管理",type=1)
	public String role_main() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"system/authority/role/index";
	}
	
	@ResponseBody
	@RequestMapping(value="grid",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:role:grid")
	@MethodName(value="系统管理->权限管理->角色管理->查询列表",type=2)
	public PageResult<SysRole> selectRole(@RequestParam(value = "offset", required = false, defaultValue = "1") Integer start, //第几页
										  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize, String sort, String order, SysRoleCondition sysRoleQUERY) throws Exception {
		PageBean<SysRole> pageBean= new PageBean<>();
		try {
			pageBean = roleService.selectRole((start / pageSize) + 1,pageSize,sort,order,sysRoleQUERY);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		PageResult<SysRole> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}
	
	/**
	 * 获取角色list，暂时未用到
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("list")
	public List<SysRole> role_list(SysRole role) throws Exception {
		List<SysRole> roleList= new ArrayList<SysRole>();
		try {
			roleList = roleService.selectRole(role);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		return roleList;
	}
	
	@ResponseBody
	@RequestMapping("getRolesTree")
	public List<Tree> getRolesTree(SysRole role) {
		List<SysRole> roleList= new ArrayList<>();
		try {
			roleList = roleService.selectRole(role);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		List<Tree> tree = new ArrayList<>();
		for (SysRole menu : roleList) {
			Tree node = new Tree();
			node.setId(menu.getId());
			node.setName(menu.getName());
			tree.add(node);
		}
		return tree;
	}
	
	
	
	/**
	 * 进入添加角色页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:role:save")
	public ModelAndView add(ModelAndView modelAndView) {
		
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/role/add");
		return modelAndView;
	}
	
	/**
	 * 新建一个角色
	 */
	@ResponseBody
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@RequiresPermissions("system:authority:role:save")
	@MethodName(value="系统管理->权限管理->角色管理->新增角色",type=2)
	synchronized public Result saveRole(@Validated RoleVO roleVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			SysRole role = new SysRole();
			role.setId(CodeUtil.getTimeSequenceAsRandomCode());
			role.setName(roleVo.getName());
			role.setSeq(roleVo.getSeq());
			role.setDescription(roleVo.getDescription());
			role.setCreatedTime(new Date());
			role.setRemark(roleVo.getRemark());
			roleService.saveRole(role);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}
	
	
	/**
	 * 进入角色查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="系统管理->权限管理->角色管理->查看角色",type=2)
	@RequiresPermissions("system:authority:role:view")
	public ModelAndView show(ModelAndView modelAndView,String id) {
		SysRole role = new SysRole();
		try {
			role = roleService.getRoleById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("role",role);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/role/view");
		return modelAndView;
	}
	
	
	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:role:update")
	public ModelAndView update(ModelAndView modelAndView,String id) {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/role/edit");
		SysRole role = new SysRole();
		try {
			role = roleService.getRoleById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("role",role);
		return modelAndView;
	}
	
	/**
	 * 修改角色
	 */
	@ResponseBody
	@RequestMapping(value="update",method = RequestMethod.POST)
	@RequiresPermissions("system:authority:role:update")
	@MethodName(value="系统管理->权限管理->角色管理->修改角色",type=2)
	synchronized public Result update(@Validated RoleVO roleVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			SysRole role = new SysRole();
			role.setId(roleVo.getId());
			role.setName(roleVo.getName());
			role.setSeq(roleVo.getSeq());
			role.setDescription(roleVo.getDescription());
			role.setModifiedTime(new Date());
			role.setRemark(roleVo.getRemark());
			roleService.updateRole(role);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}
	
	
	
	/**
	 * 删除角色
	 */
	@ResponseBody
	@RequiresPermissions("system:authority:role:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->权限管理->角色管理->删除角色",type=2)
	public Result deleteRole(String id) {
		if (id!=null) {
			try {
				int deleteCount = roleService.deleteRole(id);
				if(deleteCount<=0){
					return Result.errorAndMsg("删除失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Result.errorAndMsg("删除失败！");
			}
		}else{
			return Result.errorAndMsg("请选择需删除的记录！");
		}
		return Result.successAndMsg("删除成功！");

	}
	
	
	/**
	 * 获得当前用户的角色
	 */
	@ResponseBody
	@RequestMapping("getRoleByUserId")
	public List<SysRole> getRoleByUserId(String userId) {
		List<SysRole> roles = roleService.findRoleByUserId(userId);
		return roles;
	}

	
	/**
	 * 进入角色授权表单
	 */
	@RequestMapping(value="grant",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:role:grant")
	public ModelAndView roleGrantForm(ModelAndView modelAndView,String id) {
		modelAndView.addObject("id",id);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/role/grant");
		return modelAndView;
	}
	
	
	/**
	 * 根据roleId获得资源列表
	 */
	@ResponseBody
	@RequiresPermissions("system:authority:role:grant")
	@RequestMapping(value="findRoleResources",method=RequestMethod.GET)
	public List<SysRoleResource> findRoleResources(String roleId) {
		List<SysRoleResource> roleResources;
		roleResources = roleService.findRoleResources(roleId);
		return roleResources;
	}
	
	
	/**
	 * 授权角色资源
	 */
	@ResponseBody
	@RequestMapping(value="grant",method=RequestMethod.POST)
	@RequiresPermissions("system:authority:role:grant")
	@MethodName(value="系统管理->权限管理->角色管理->授权角色",type=2)
	public Result grantRoleResource(String ids, String roleId) {
		try {
			roleService.grantRoleResource(ids,roleId);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败");
		}
		return Result.successAndMsg("保存成功");
	
	}
	
}
